package com.firmiana.jt809.parser;

import java.io.UnsupportedEncodingException;

/**
 * @author hucl
 * @date 2020/8/25 17:55
 */
public class MessageParser {
    private String msg;
    private int index;

    public MessageParser(String msg) {
        this.msg = msg;
    }

    public MessageParser(String msg, int index) {
        this.msg = msg;
        this.index = index;
    }

    public String getString(int byteNum) {
        int endIndex = index + byteNum * 2;
        String s = msg.substring(index, endIndex);
        index = endIndex;
        s = hexToString(s);
        int index = s.indexOf('\0');
        if (index >= 0) {
            s = s.substring(0, index);
        }
        return s;
    }

    public static String hexToString(String s) {
        byte[] baKeyword = new byte[s.length() / 2];
        for (int i = 0; i < baKeyword.length; i++) {
            int start = i * 2;
            baKeyword[i] = (byte) (0xff & Integer.parseInt(
                    s.substring(start, start + 2), 16));
        }
        try {
            s = new String(baKeyword, "gbk");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return s;
    }

    public int getInt(int byteSize) {
        int endIndex = index + byteSize * 2;
        String s = msg.substring(index, endIndex);
        index = endIndex;
        // long x = Long.valueOf(s, 16);
        return Integer.valueOf(s, 16);
    }

    public long getLong(int byteNum) {
        int endIndex = index + byteNum * 2;
        String s = msg.substring(index, endIndex);
        index = endIndex;
        return Long.valueOf(s, 16);
    }

}
